package com.bjbn.controller;

import com.bjbn.bean.MonitorResponse;
import com.bjbn.bean.QueueInfo;
import com.bjbn.service.RabbitmqMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * RabbitMQ监控控制器
 * 
 * @author bjbn
 */
@Slf4j
@RestController
@RequestMapping("/api/rabbitmq")
public class RabbitmqController {

    @Autowired
    private RabbitmqMonitorService monitorService;

    /**
     * 获取所有队列的监控状态
     *
     * @return 监控响应
     */
    @GetMapping("/status")
    public ResponseEntity<MonitorResponse> getStatus() {
        try {
            log.info("获取RabbitMQ监控状态请求");
            MonitorResponse response = monitorService.getMonitorStatus();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取监控状态时发生错误", e);
            MonitorResponse errorResponse = new MonitorResponse(
                    500,
                    "获取监控状态失败: " + e.getMessage(),
                    LocalDateTime.now(),
                    null
            );
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取指定队列的状态
     *
     * @param queueName 队列名称
     * @return 队列信息
     */
    @GetMapping("/status/{queueName}")
    public ResponseEntity<QueueInfo> getQueueStatus(@PathVariable String queueName) {
        try {
            log.info("获取队列 {} 的监控状态", queueName);
            QueueInfo queueInfo = monitorService.getQueueStatus(queueName);
            if (queueInfo != null) {
                return ResponseEntity.ok(queueInfo);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取队列状态时发生错误", e);
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 获取所有队列列表
     *
     * @return 队列列表
     */
    @GetMapping("/queues")
    public ResponseEntity<List<QueueInfo>> getAllQueues() {
        try {
            log.info("获取所有RabbitMQ队列列表");
            List<QueueInfo> queues = monitorService.getAllQueues();
            return ResponseEntity.ok(queues);
        } catch (Exception e) {
            log.error("获取队列列表时发生错误", e);
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 健康检查接口
     *
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        return ResponseEntity.ok("RabbitMQ Status API is running");
    }
}